package com.atguigu.gmall.order.mq;

import com.atguigu.gmall.order.entity.OrderDetail;
import com.atguigu.gmall.order.service.OrderDetailService;
import com.google.common.collect.Lists;

import com.atguigu.gmall.common.config.mq.service.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.msg.OrderCreateMsg;
import com.atguigu.gmall.msg.OrderPayedMsg;
import com.atguigu.gmall.msg.WareStockMsg;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.order.service.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-23 20:59
 **/
@Slf4j
@Component
public class OrderPayedListener {
    @Autowired
    MqService mqService;
    @Autowired
    OrderBizService orderBizService;
    @Autowired
    OrderDetailService orderDetailService;

    @RabbitListener(queues = MqConst.ORDER_PAYED_QUEUE)
    public void closeOrder(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            OrderPayedMsg orderPayedMsg = mqService.getMessageContent(message, OrderPayedMsg.class);
            // 对外交易号+用户id =》 寻找订单
            OrderInfo orderInfo = orderBizService.getOrderInfo(orderPayedMsg.getOutTradeNo());
            // 未支付&已关闭=》改为已支付
            orderBizService.changeOrderStatusToPayed(orderInfo.getUserId(), orderInfo.getId());
            log.info("订单状态修改为已支付");
            // TODO 【库存】 给库存系统发消息，让他开始减库存（路由键：queue.ware.stock）
            WareStockMsg wareStockMsg = getWareStockMsg(orderInfo);
            mqService.convertAndSend(MqConst.WARE_STOCK_EXCHANGE, MqConst.WARE_STOCK_RK, wareStockMsg);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("关闭订单失败，原因是：{},正在重试...", e);
            mqService.retry(message, channel, MqConst.ORDER_RETRY_COUNT);
        }
    }

    private WareStockMsg getWareStockMsg(OrderInfo orderInfo) {
        WareStockMsg wareStockMsg = new WareStockMsg();
        wareStockMsg.setOrderId(orderInfo.getId());
        wareStockMsg.setConsignee(orderInfo.getConsignee());
        wareStockMsg.setConsigneeTel(orderInfo.getConsigneeTel());
        wareStockMsg.setOrderComment(orderInfo.getOrderComment());
        wareStockMsg.setOrderBody(orderInfo.getTradeBody());
        wareStockMsg.setDeliveryAddress(orderInfo.getDeliveryAddress());
        wareStockMsg.setPaymentWay("2"); // 在线支付
        // 查询订单买了哪些商品
        List<WareStockMsg.Sku> skus = orderDetailService.getDetails(orderInfo.getUserId(), orderInfo.getId()).stream().map((item) -> {
            WareStockMsg.Sku sku = new WareStockMsg.Sku();
            sku.setSkuId(item.getSkuId());
            sku.setSkuNum(item.getSkuNum());
            sku.setSkuName(item.getSkuName());
            return sku;
        }).collect(Collectors.toList());
        wareStockMsg.setDetails(skus);
        return wareStockMsg;
    }
}
